package com.taotao.manage.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.github.abel533.entity.Example;
import com.github.abel533.mapper.Mapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.manage.pojo.BasePojo;

public class BaseService<T extends BasePojo> {

	@Autowired
	public Mapper<T> mapper;
	
	@Autowired
	public PropertieService propertieService;

	/**
	 * 根据条件查询多条数据所有
	 * 
	 * @param record
	 * @return
	 */
	public List<T> queryByRecord(T record) {
		return mapper.select(record);
	}

	/**
	 * 根据主键进行查询
	 * 
	 * @param id
	 * @return
	 */
	public T queryById(Long id) {
		return this.mapper.selectByPrimaryKey(id);
	}

	/**
	 * 查询全部
	 * 
	 * @return
	 */
	public List<T> queryAll() {
		return this.mapper.select(null);
	}

	/**
	 * 根据条件查询1条数据。
	 * 
	 * @param record
	 * @return
	 */
	public T queryOne(T record) {
		return this.mapper.selectOne(record);
	}

	/**
	 * 根据条件分页查询
	 * 
	 * @param record
	 * @return
	 */
	public PageInfo<T> queryPageListByWhere(T record, Integer page, Integer rows) {
		PageHelper.startPage(page, rows);
		List<T> list = this.mapper.select(record);
		return new PageInfo<>(list);
	}

	/**
	 * 根据主键进行删除
	 * 
	 * @param id
	 * @return
	 */
	public Integer deleteById(Long id) {
		return this.mapper.deleteByPrimaryKey(id);
	}

	/**
	 * 插入数据
	 * 
	 * @param record
	 * @return
	 */
	public Boolean save(T record) {
		record.setCreated(new Date());
		record.setUpdated(record.getCreated());
		 
		int insert = this.mapper.insert(record);
		if(insert==1){
			return true;
		}
		return false;
	}

	/**
	 * 根据主键更新数据
	 * 
	 * @param record
	 * @return
	 */
	public Boolean update(T record) {
		record.setUpdated(new Date());
		 int update = this.mapper.updateByPrimaryKeySelective(record);
		 if(update==1) return true;
		 return false;
	}

	/**
	 * 根据主键删除一条数据
	 * 
	 * @param key
	 * @return
	 */
	public Integer deleteById(Object key) {
		return this.mapper.deleteByPrimaryKey(key);
	}

	/**
	 * 根据主键批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Integer deleteByIds(String property, Class clazz, List<Object> ids) {
		Example example = new Example(clazz);
		example.createCriteria().andIn(property, ids);
		return this.mapper.deleteByExample(example);
	}

	/**
	 * 根据条件删除
	 * 
	 * @param record
	 * @return
	 */
	public Integer deleteByWhere(T record) {
		return this.mapper.delete(record);
	}
	
	/**
	 * 根据条件查询数量
	 * @param queryObj
	 * @return
	 */
	public Integer count(T record){
		return this.mapper.selectCount(record);
	}

}
